package crowMessenger;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class ChatPanel extends JPanel implements Runnable{
	private static final long serialVersionUID = -1670445370142190145L;
	private Dimension dim = new Dimension(500, 400);
	private Color bg = Color.LIGHT_GRAY;
	private Buddy buddy;
	private JScrollPane textScrollPane;//contains TEXT
	private JTextArea TEXT; //the plane with the sent & received text chats
	private JScrollPane preTextScrollPane;//contains preTEXT
	private JTextArea preTEXT; //the typed text before being sent
	private ChatManager chatManager;
	private Chat chat;

	public ChatPanel(Buddy buddy){
		this.buddy = buddy;
		setLayout(new BorderLayout());
		setPreferredSize(dim);
		setBackground(bg);

		chatManager = buddy.getConnection().getChatManager();

		TEXT = new JTextArea();
		textScrollPane = new JScrollPane(TEXT,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

		preTEXT = new JTextArea();
		preTextScrollPane = new JScrollPane(preTEXT,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

		add(textScrollPane,BorderLayout.CENTER);
		add(preTextScrollPane,BorderLayout.SOUTH);
		run();
	}

	@Override
	public void run() {
		// Receiving messages
		chat = chatManager.createChat(buddy.getUsername(), new MessageListener() {
			@Override
			public void processMessage(Chat arg0, Message arg1) {
				if(arg1.getBody() != null) //before and after each incoming msg , there is null msg
					TEXT.append("\n"+arg1.getFrom()+" : "+arg1.getBody());
			}
		});
		// Sending messages
		preTEXT.addKeyListener(new KeyListener() {
			@Override
			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub

			}
			@Override
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub

			}
			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub
				if(e.getKeyCode() == KeyEvent.VK_ENTER){
					try {
						chat.sendMessage(preTEXT.getText());
					} catch (XMPPException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
					TEXT.append("\n"+buddy.getConnection().getUser()+" : "+preTEXT.getText());
					preTEXT.setText(null);
				}
			}
		});
	}
}
